package com.brainhealth.web.controller.customer;

import cn.hutool.core.convert.Convert;
import com.brainhealth.common.annotation.Anonymous;
import com.brainhealth.common.annotation.Log;
import com.brainhealth.common.annotation.RepeatSubmit;
import com.brainhealth.common.core.controller.BaseController;
import com.brainhealth.common.core.domain.AjaxResult;
import com.brainhealth.common.core.page.TableDataInfo;
import com.brainhealth.common.enums.BusinessType;
import com.brainhealth.common.utils.DateUtils;
import com.brainhealth.common.utils.StringUtils;
import com.brainhealth.common.utils.ip.IpUtils;
import com.brainhealth.common.utils.poi.ExcelUtil;
import com.brainhealth.customer.domain.Customer;
import com.brainhealth.customer.domain.InitUserParam;
import com.brainhealth.customer.domain.vo.CustomerScheduleVO;
import com.brainhealth.customer.service.ICustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 会员信息Controller
 * 
 * @author wolong
 * @date 2023-04-27
 */
@RestController
@RequestMapping("/customer/customer")
public class CustomerController extends BaseController
{
    @Autowired
    private ICustomerService customerService;

    /**
     * 查询会员信息列表
     */
    @PreAuthorize("@ss.hasPermi('customer:customer:list')")
    @GetMapping("/list")
    public TableDataInfo list(Customer customer)
    {
        startPage();
        List<Customer> list = customerService.selectCustomerList(customer);
        return getDataTable(list);
    }

    /**
     * 导出会员信息列表
     */
    @PreAuthorize("@ss.hasPermi('customer:customer:export')")
    @Log(title = "会员信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Customer customer)
    {
        List<Customer> list = customerService.selectCustomerList(customer);
        ExcelUtil<Customer> util = new ExcelUtil<Customer>(Customer.class);
        util.exportExcel(response, list, "会员信息数据");
    }

    /**
     * 获取会员信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('customer:customer:query')")
    @GetMapping(value = "/{customerId}")
    public AjaxResult getInfo(@PathVariable("customerId") Long customerId)
    {
        return success(customerService.selectCustomerByCustomerId(customerId));
    }

    /**
     * 新增会员信息
     */
    @PreAuthorize("@ss.hasPermi('customer:customer:add')")
    @Log(title = "会员信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Customer customer)
    {
        return toAjax(customerService.insertCustomer(customer));
    }

    /**
     * 新增会员白名单
     */
    @PreAuthorize("@ss.hasPermi('customer:customer:add')")
    @Log(title = "会员信息", businessType = BusinessType.INSERT)
    @PostMapping("/addWhiteListCustomer")
    public AjaxResult addWhiteListCustomer(@RequestBody Map<String, String> map)
    {
        String phone = map.get("phone");
        int result = customerService.addWhiteListCustomer(phone);
        if (result > 0)
        {
            return AjaxResult.success("添加白名单用户成功！");
        }
        return AjaxResult.error("添加白名单用户失败！");
    }

    /**
     * 添加5天训练体验会员
     * @return
     */
    @Anonymous
    @RepeatSubmit
    @PostMapping("/addExperienceCustomer")
    public AjaxResult addExperienceCustomer(@RequestBody Map<String, String> map)
    {
        String phone = map.get("phone");
        String smsCode = map.get("smsCode");
        String inviteCustomerId = map.get("shareId");
        if (StringUtils.isNullOrEmpty(smsCode))
        {
            return AjaxResult.error("验证码不能为空！");
        }
        String result = customerService.addExperienceCustomer(inviteCustomerId,phone, smsCode);
        if (!StringUtils.isNullOrEmpty(result))
        {
            return AjaxResult.success("添加体验用户成功！", result);
        }
        return AjaxResult.error("添加体验用户失败！");
    }

    @Anonymous
    @GetMapping("/initExperience")
    public AjaxResult initExperience(String phone)
    {
        boolean result = customerService.initExperience(phone);
        if (result)
        {
            return AjaxResult.success("初始化成功！");
        }
        return AjaxResult.error("初始化失败！");
    }

    /**
     * 修改会员信息
     */
    @PreAuthorize("@ss.hasPermi('customer:customer:edit')")
    @Log(title = "会员信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Customer customer)
    {
        return toAjax(customerService.updateCustomer(customer));
    }


    @PreAuthorize("@ss.hasPermi('customer:customer:edit')")
    @Log(title = "会员信息", businessType = BusinessType.UPDATE)
    @PostMapping("/modifyCustomerPhone")
    public AjaxResult modifyCustomerPhone(@RequestBody Map<String, String> map)
    {
        String oldPhone = map.get("oldPhone");
        String newPhone = map.get("newPhone");
        boolean result = customerService.modifyCustomerPhone(oldPhone, newPhone);
        if (result)
        {
            return AjaxResult.success("修改会员注册手机号成功！");
        }
        return AjaxResult.error("修改会员注册手机号失败！");
    }

    @PreAuthorize("@ss.hasPermi('customer:customer:edit')")
    @Log(title = "会员信息", businessType = BusinessType.UPDATE)
    @PostMapping("/addCustomerBlack")
    public AjaxResult addCustomerBlack(@RequestBody Customer customer)
    {
        boolean result = customerService.addCustomerBlack(customer);
        if (result)
        {
            return AjaxResult.success("操作会员黑名单成功！");
        }
        return AjaxResult.error("操作会员白名单失败！");
    }

    /**
     * 删除会员信息
     */
    @PreAuthorize("@ss.hasPermi('customer:customer:remove')")
    @Log(title = "会员信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{customerIds}")
    public AjaxResult remove(@PathVariable Long[] customerIds)
    {
        return toAjax(customerService.deleteCustomerByCustomerIds(customerIds));
    }


    /**
     * 发送短信验证码
     *
     * @param map
     * @return
     */
    @Anonymous
    @RepeatSubmit
    @PostMapping("/sendSmsCode")
    public AjaxResult sendSmsCode(@RequestBody Map<String, Object> map)
    {
        String phone = map.get("phone").toString();
        if (StringUtils.isEmpty(phone))
        {
            return AjaxResult.error("手机号不能为空");
        }
        boolean result = customerService.SendSmsCode(phone);
//        boolean result = customerService.SendSmsCodeTest(phone);
        if (result)
        {
            return AjaxResult.success("发送短信验证码成功！");
        }
        return AjaxResult.error("短信发送重复或短信发送失败！");
    }

    /**
     * 会员登录
     *
     * @param map
     * @return
     */
    @Anonymous
    @RepeatSubmit
    @PostMapping("/login")
    public AjaxResult customerLogin(@RequestBody Map<String, Object> map)
    {
        String phone = map.get("phone").toString();
        String smsCode = map.get("smsCode").toString();
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(smsCode))
        {
            return AjaxResult.error("手机号或验证码不能为空！");
        }
        String token = customerService.customerLogin(phone, smsCode);
        return AjaxResult.success("会员登录成功！", token);
    }

    /**
     * 用户退出登录
     *
     * @param request
     * @return
     */
    @Anonymous
    @PostMapping("/loginOut")
    public AjaxResult customerLoginOut(HttpServletRequest request)
    {
        boolean result = customerService.customerLoginOut(request);
        if (result)
        {
            return AjaxResult.success("会员退出登录成功！");
        }
        return AjaxResult.error("会员退出登录失败！");
    }

    /**
     * 会员注册
     *
     * @param map
     * @return
     */
    @Anonymous
    @RepeatSubmit
    @PostMapping("/register")
    public AjaxResult customerRegister(HttpServletRequest request, @RequestBody Map<String, Object> map)
    {
        String phone = map.get("phone").toString();
        String smsCode = map.get("smsCode").toString();
        String mechanismId = "";
        if (map.get("mechanismId") != null)
        {
            mechanismId = map.get("mechanismId").toString();
        }
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(smsCode))
        {
            return AjaxResult.error("手机号或验证码不能为空！");
        }
        String ip = IpUtils.getIpAddr(request);
        String token = customerService.customerRegister(ip, phone, smsCode, mechanismId);
        if (!StringUtils.isEmpty(token))
        {
            return AjaxResult.success("会员注册成功！", token);
        }
        return AjaxResult.error("会员注册失败！");
    }

    /**
     * 使用token获取会员信息
     *
     * @param request
     * @return
     */
    @Anonymous
    @PostMapping("/getCustomer")
    public AjaxResult getCustomerInfo(HttpServletRequest request)
    {
        Customer customer = customerService.getCustomerInfo(request);
        if (customer != null)
        {
            return AjaxResult.success("获取会员信息成功！", customer);
        }
        return AjaxResult.error("获取会员信息失败！请重新登录！");
    }

    /**
     * 更新会员信息
     *
     * @param customer
     * @return
     */
    @Anonymous
    @PostMapping("/updateCustomer")
    public AjaxResult updateCustomerInfo(@RequestBody Customer customer)
    {
        boolean result = customerService.updateCustomerInfo(customer);
        if (result)
        {
            return AjaxResult.success("更新会员信息成功！");
        }
        return AjaxResult.error("更新会员信息失败！");
    }

    @Anonymous
    @PostMapping("/getTimeBetween")
    public AjaxResult getTimeBetween(@RequestBody Map<String, Object> map)
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try
        {
            Date bTime = sdf.parse(map.get("bTime").toString());
            Date eTime = sdf.parse(map.get("eTime").toString());
            return AjaxResult.success(DateUtils.differentSecondByMillisecond(eTime, bTime));
        } catch (Exception e)
        {
            logger.error("日期格式错误", e);
            return AjaxResult.error("日期格式错误");
        }
    }

    /**
     * 会员签到
     *
     * @param request
     * @return
     */
    @Anonymous
    @PostMapping("/customerSignIn")
    public AjaxResult customerSignIn(HttpServletRequest request)
    {
        boolean result = customerService.customerSignIn(request);
        if (result)
        {
            return AjaxResult.success("会员签到成功！");
        }
        return AjaxResult.error("会员已签到！");
    }

    /**
     * 初始化用户
     *
     * @return
     */
    @Anonymous
    @PostMapping("/initUser")
    public AjaxResult initUser(@RequestBody InitUserParam initUserParam)
    {
        Integer result = customerService.initCustomer(initUserParam);
        if (null == result)
        {
            return error();
        }
        return success(result);
    }

    /**
     * 获取会员所有的日程信息
     *
     * @param request
     * @return
     */
    @Anonymous
    @PostMapping("/getCustomerScheduleInfo")
    public AjaxResult getCustomerScheduleInfo(HttpServletRequest request)
    {
        CustomerScheduleVO customerScheduleVo = customerService.getCustomerScheduleInfo(request);
        return AjaxResult.success(customerScheduleVo);
    }

    //生成用户唯一ID
    @Anonymous
    @PostMapping("/createCustomerShareLink")
    public AjaxResult createCustomerShareLink(HttpServletRequest request)
    {
        return AjaxResult.success(customerService.createCustomerShareLink(request));
    }

}
